/*
 * Powered By dico
 * Since 2017 - 2018
 */
package com.seeyoui.kensite.bussiness.exam.examResult.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.seeyoui.kensite.bussiness.exam.examResult.domain.ExamResult;
import com.seeyoui.kensite.bussiness.exam.examResult.service.ExamResultService;
import com.seeyoui.kensite.bussiness.exam.examResult.service.MarkingService;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.Result;
import com.seeyoui.kensite.common.util.excel.ExportExcel;
import com.seeyoui.kensite.framework.system.util.UserUtils;
/**
 * ExamResult
 * @author dico
 * @version 2.0
 * @since 1.0
 * @date 2018-01-08
 */

@Controller
@RequestMapping(value = "exam/examResult")
public class ExamResultController extends BaseController {
	
	@Autowired
	private ExamResultService examResultService;
	@Autowired
	private MarkingService markingService;
	
	
	/**
	 * 展示列表页面
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:examResult:view")
	@RequestMapping(value = "/{page}")
	public ModelAndView view(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page) throws Exception {
		return new ModelAndView("bussiness/exam/examResult/"+page, modelMap);
	}
	
	/**
	 * 根据ID查询单条数据
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:examResult:select")
	@RequestMapping(value = "/data/{id}")
	@ResponseBody
	public Object data(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String id) throws Exception {
		ExamResult examResult = examResultService.findOne(id);
		return examResult;
	}
	
	/**
	 * 根据ID查询单条数据并返回相应表单
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:examResult:view")
	@RequestMapping(value = "/form/{page}/{id}")
	public ModelAndView form(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page, @PathVariable String id) throws Exception {
		ExamResult examResult = examResultService.findOne(id);
		modelMap.put("examResult", examResult);
		return new ModelAndView("bussiness/exam/examResult/"+page, modelMap);
	}
	
	/**
	 * 获取列表展示数据
	 * @param modelMap
	 * @param examResult
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:examResult:select")
	@RequestMapping(value = "/list/data", method=RequestMethod.POST)
	@ResponseBody
	public Object listData(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ExamResult examResult) throws Exception {
		List<ExamResult> examResultList = examResultService.findList(examResult);
		int total = examResultService.findTotal(examResult);
		EasyUIDataGrid eudg = new EasyUIDataGrid();
		eudg.setTotal(String.valueOf(total));
		eudg.setRows(examResultList);
		return eudg;
	}
	
	/**
	 * 获取列表展示数据带分页器用于jsp自己做分页
	 * @param modelMap
	 * @param examResult
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:examResult:view")
	@RequestMapping(value = "/list/page", method=RequestMethod.POST)
	@ResponseBody
	public Object listPage(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ExamResult examResult) throws Exception {
		List<ExamResult> examResultList = examResultService.findList(examResult);
		int total = examResultService.findTotal(examResult);
		Page<ExamResult> page = new Page<ExamResult>(examResult.getPage(), examResult.getRows(), total);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("rows", examResultList);
		dataMap.put("page", page);
		return dataMap;
	}
	
	/**
	 * 获取所有数据
	 * @param modelMap
	 * @param examResult
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:examResult:select")
	@RequestMapping(value = "/list/all", method=RequestMethod.POST)
	@ResponseBody
	public Object listAll(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ExamResult examResult) throws Exception {
		List<ExamResult> examResultList = examResultService.findAll(examResult);
		return examResultList;
	}
	
	/**
	 * 保存新增的数据
	 * @param modelMap
	 * @param examResult
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:examResult:insert")
	@RequestMapping(value = "/save", method=RequestMethod.POST)
	@ResponseBody
	public String save(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ExamResult examResult) throws Exception {
		if (!beanValidator(modelMap, examResult)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		examResultService.save(examResult);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 保存修改的数据
	 * @param modelMap
	 * @param examResult
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:examResult:update")
	@RequestMapping(value = "/update", method=RequestMethod.POST)
	@ResponseBody
	public String update(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ExamResult examResult) throws Exception {
		if (!beanValidator(modelMap, examResult)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		examResultService.update(examResult);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 删除数据库
	 * @param modelMap
	 * @param examResultId
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:examResult:delete")
	@RequestMapping(value = "/delete", method=RequestMethod.POST)
	@ResponseBody
	public String delete(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, String id) throws Exception {
		List<String> listId = Arrays.asList(id.split(","));
		examResultService.delete(listId);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 假删除
	 * @param modelMap
	 * @param examResult
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:examResult:delete")
	@RequestMapping(value = "/remove", method=RequestMethod.POST)
	@ResponseBody
	public String remove(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ExamResult examResult) throws Exception {
		examResultService.remove(examResult);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 导出Excel数据
	 * @param modelMap
	 * @param examResult
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:examResult:export")
	@RequestMapping(value = "/export")
	public String export(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ExamResult examResult) throws Exception {
		String fileName = DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
		List<ExamResult> examResultList = examResultService.findAll(examResult);
		new ExportExcel(null, ExamResult.class).setDataList(examResultList).write(response, fileName).dispose();
		return null;
	}
	
	
	/**
	 * 提交考试试卷
	 * @param session
	 * @param response
	 * @param request
	 * @param examId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/submit", method=RequestMethod.POST)
	@ResponseBody
	public Result submit(HttpServletRequest request, String data) throws Exception {
		String json = data.replaceAll("&quot;", "\"");
		String examId = (String)JSONPath.read(json, "$.examId");
		JSONObject answer = (JSONObject)JSONPath.read(json, "$.answer");
		examResultService.save(UserUtils.getUser(request).getId(), examId);
		ExamResult examResult = examResultService.findByUserIdAndExamId(UserUtils.getUser(request).getId(), examId);
		if(null == examResult) {
			logger.error("该考试结果记录不存在：examId=" + examId + "  userId=" + UserUtils.getUser(request).getId());
			return Result.failure("该考试结果记录不存在：examId=%s userId=%s", examId, UserUtils.getUser(request).getId());
		}
		examResult.setSubmitTime(new Date());
		examResult.setResult(answer.toJSONString());
		examResultService.update(examResult);

		// 异步线程评分
		markingService.marking(examId);

		return Result.success(null, "试卷提交成功！");
	}
}